<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<link rel="shortcut icon" href="./favicon.ico" type="image/x-icon">
<title>全国地图省市区销售额排行</title> 
<script src="js/jquery.min.js"></script>
<script src="js/echarts.min.js"></script>
<!-- <script src=" https://cdn.jsdelivr.net/npm/echarts@5.5.0/dist/echarts.min.js "></script> -->

<script src="https://webapi.amap.com/maps?v=2.0&key=73cddabc2173e0166a622f4483d3592a&plugin=AMap.DistrictSearch"></script>
<script src="https://webapi.amap.com/maps?v=2.0&key=73cddabc2173e0166a622f4483d3592a" type="text/javascript"></script> 
<script src="https://webapi.amap.com/ui/1.1/main.js"></script>
<script src="https://echarts.baidu.com/resource/echarts-gl-latest/dist/echarts-gl.min.js"></script>

<style type="text/css">
	
	body{background-color: white}
	#chart-panel {
		width:33%;
		height: 770px;
		left: 33%;
		right: 0;
		top: 200px;
		bottom: 0;
		margin-top: 10px;
		background-size: 100% auto;
		border: 1px red solid;
		/*background-color: #0E0E29*/
	} 

	#chart-panel .back{opacity: 0.5; position:absolute;left: 25px;top: 20px;color:#b3efff;font-size: 16px;cursor: not-allowed;z-index:100;} 
</style>
</head>
<body style="background:url(http://admin.zjmaoyan.com/Images/home/my_bgbox.png) no-repeat;background-size:cover;"> 
<div id="chart-panel"></div>
<script type="text/javascript">


var myChart = echarts.init(document.getElementById("chart-panel"));
$('<div class="back">返 回</div>').appendTo($('#chart-panel')); 

//返回按钮
$('.back').click(function() {
  //$(this).css({"cursor":"not-allowed","opacity":"0.5"})
  if (parentInfo.length === 1) {
		
		return;
   }
   if(parentInfo.length===2)
   {
	  $(this).css({"cursor":"not-allowed","opacity":"0.5"})	
   }
   parentInfo.pop() //删除最后一个元素
   console.log("返回按钮："+parentInfo[parentInfo.length - 1].code)
  init(parentInfo[parentInfo.length - 1].code)
})
  
var geoJson = {}
var parentInfo = [{cityName: '全国',code: 100000}]
var currentIndex = 0



$('.back').css({"cursor":"pointer","opacity":"1"})


init(100000)

function init(adcode){
  getGeoJson(adcode).then(data => {
	geoJson = data;
	getMapData()
  }) 
}
	
//这里封装了，直接可以拿过来用
function getGeoJson(adcode, childAdcode = '') {
  	return new Promise((resolve, reject) => {
		function insideFun(adcode, childAdcode) {
			AMapUI.loadUI(['geo/DistrictExplorer'], DistrictExplorer => {
				var districtExplorer = new DistrictExplorer();
				districtExplorer.loadAreaNode(adcode, function(error, areaNode) {
					//console.log("111"+JSON.stringify(areaNode));
				if (error) {
					//console.error(error);
					reject(error);
					return;
				}
				let Json = areaNode.getSubFeatures();
				if (Json.length === 0) {
					let parent = areaNode._data.geoData.parent.properties.acroutes;
					insideFun(parent[parent.length - 1], adcode);
					return;
				}
				if (childAdcode) {
					Json = Json.filter(item => {
					return item.properties.adcode == childAdcode;
					});
				}
				let mapJson = {
					features: Json
				};
				resolve(mapJson);
				});
			});
		}
		insideFun(adcode, childAdcode);
  	});
}
	  
//获取数据    
function getMapData() {
	let mapData = [];
	geoJson.features.forEach(item => {
		// console.log( item.properties.name);
		mapData.push({
			name: item.properties.name,
			value: 123,
			cityCode: item.properties.adcode,
			areaId:109
		})
	})
	// console.log("-------------");
	console.log(mapData);
    // console.log("-------------");
	initEchartMap(mapData)
}
	  
//渲染echarts
function initEchartMap(mapData) {

	// console.log(mapData);
    mapData.forEach(c=>{
		c.name=c.name.replace(/(省|市|自治区|回族|维吾尔|壮族|特别行政区)/g,'')	
	})
	// console.log(mapData)
	//这里做个切换，全国的时候才显示南海诸岛  只有当注册的名字为china的时候才会显示南海诸岛
	// console.log(geoJson)

	//为了使默认的省的名字过长  进行的处理。同时把一些地方不显示
	geoJson.features.forEach(item => {
		item.properties.name=item.properties.name.replace(/(省|市|自治区|回族|维吾尔|壮族|特别行政区)/g,'');
	
		if(item.properties.adcode==150000)
		{
			//item.properties.centroid=[113.8668, 22.8076];
			//item.properties.center=[113.8668, 22.8076];
		}
	})
    
	//解决不能通过lable 属性 控制地图  地区名+数量
	mapData.forEach(c=>{
		// console.log("mapData foreach...")
		// console.log(c.name);
		var name=c.name.replace(/[0-9]/g,'');
		var num=c.value;
		// console.log(geoJson.features);
		geoJson.features.forEach(item => {
			if(item.properties.name==name)
			{
				item.properties.name="";
				item.properties.name=name
				return;
			}
		})
		c.name="";
		c.name=name //+num;
	})

	echarts.registerMap(parentInfo.length === 1 ? 'china' : 'map', geoJson);
	// console.log(parentInfo);
	console.log(mapData);
  	var option = {
			// backgroundColor: '#012248',
			title: [
				{
					left: 'center',
					top: 20,
					text: parentInfo[parentInfo.length - 1].cityName,
					textStyle: {
						color: '#b3efff',
						fontSize: 16
					},
				}
			],
			tooltip: {
				formatter: p => {
						//这里是鼠标放上去显示的
						let val=p.value;
						if(window.isNaN(val)){
							return val=0;
						}
						return p.name+'<br>数量：'+p.value //鼠标悬浮上去显示
			    }
			},
			series: [{  //最外层鼠标经过显示的黑框
				map: parentInfo.length === 1? 'china' : 'map',
				type: 'map',
				zoom:1.2,
				label: {
					normal: { 
                                show: true, //是否显示地图省份得名称
                                textStyle: {
                                    color: "#1e1e1e"
                                },
                                formatter:function(e)
                                {
									// console.log(e);
                                    var num=0;
                                    if(!isNaN(e.value))
                                    {
                                        num=e.value                            
                                    }
                                    return `{name|${e.name}}{value|${num}}`;  // 地名和数量一起显示                        
                                },
                                rich: {
                                        name:{
                                            fontSize: 10,
                                            backgroundColor:'white',
                                            padding:[3,2,2,2],
                                            verticalAlign:'middle',
                                            borderRadius:[2,0,0,2]
                                        },
                                        value:{
                                            color: "white",
                                            padding:[3,2,2,2],
                                            fontSize: 10,
                                            backgroundColor:'#ff9600',
                                            verticalAlign:'middle',
                                            borderRadius:[0,2,2,0]
                                        }
                                        
                                    }
                                
                            }   
				},
				itemStyle: {
					normal: {
						areaColor: {
                                    type: 'linear',
                                    x: 1,
                                    y: 1,
                                    x2: 0,
                                    y2: 0,
                                    colorStops: [
                                        { offset: 0, color: '#0c3a67' },
                                        { offset: 1, color: '#0c4179' }
                                    ],
                                    global: false // 缺省为 false
                                },
						borderColor: '#53D9FF',
						borderWidth: 1
					},
					emphasis: { // 选中后颜色变化
						label: {show: true},
						areaColor: '#8dd7fc',
						borderWidth: 1.6,
						shadowBlur: 25
                    }
				},
				data: mapData,

		  	}
			  
		]
		
	}
	myChart.setOption(option, true)
	//点击前解绑，防止点击事件触发多次
	myChart.off('click');
	myChart.on('click', echartsMapClick);

}

//echarts点击事件
function echartsMapClick(params) {
    console.log('点击')
	// console.log("params="+JSON.stringify(params.data));
    console.log("纪录："+JSON.stringify(parentInfo));

	$('.back').css({"cursor":"pointer","opacity":"1"})
	//console.log(params.data);
	if (!params.data||params.data.name=='') {
		return
	} else { 
		//如果当前是最后一级，那就直接return  
		if (parentInfo[parentInfo.length - 1].code == params.data.cityCode) {
		  return
		}
		// 4 级联动时候判断 
		if(parentInfo.length>2){
			// 这里进入最后一级地图
			// 这里进入最后一级地图
			console.log(isShowLastMap(parentInfo));
			if(!isShowLastMap(parentInfo))
			{
				return;			
			}
			let data = params.data
			parentInfo.push({
				cityName: data.name,
				code: data.cityCode
			})
			var lastCode=params.data.cityCode;
			lastMap(lastCode);
			return;
		}
		if(parentInfo.length==2)
		{
			 if(parentInfo[1].code==500000)	
			 {
				 alert("重庆最后一张图");
				 return;
			 }	
		}
		let data = params.data
		parentInfo.push({
			cityName: data.name,
			code: data.cityCode
		})
		// 3级联动判断，最后一级跳转到最后一张地图
        // console.log(data.cityCode)
		console.log("纪录2："+JSON.stringify(parentInfo));
		init(data.cityCode)
	}
}



// 最后一级地图js

function lastMap(adcode)
{
	
	// myChart.clear();
	var dataList=[ 
            {name: '安地镇', value: 10024,areaId:'1'},
            {name: '雅畈镇', value: 10024,areaId:'2'}
        ];
	$.get('geojson/ZheJiang/'+adcode+'.json', function (geoJson) {
			// myChart.hideLoading();
            echarts.registerMap('', geoJson);

            myChart.setOption(option = {
                tooltip: {
                    formatter:function(params){
                        var num=0;
                        if(!isNaN(params.value))
                        {
                            num=params.value                            
                        }
                        return params.name+'<br>数量：'+num //鼠标悬浮上去显示
                    }
                },
                series: [
                    {
                        type: 'map',
                        zoom:1.2,
                        mapType: '', // 自定义扩展图表类型
                        label:{
                            normal: { //静态的时候展示样式
                                show: true, //是否显示地图省份得名称
                                textStyle: {
                                    color: "#1e1e1e"
                                },
                                formatter:function(e)
                                {
                                    var num=0;
                                    if(!isNaN(e.value))
                                    {
                                        num=e.value                            
                                    }
                                    return `{name|${e.name}}{value|${num}}`;  // 地名和数量一起显示                        
                                },
                                rich: {
                                    // `{name|${e.name}}{value|${e.value}}` 样式
                                        name:{
                                            fontSize: 10,
                                            backgroundColor:'white',
                                            padding:[3,2,2,2],
                                            verticalAlign:'middle',
                                            borderRadius:[2,0,0,2]
                                        },
                                        value:{
                                            color: "white",
                                            padding:[3,2,2,2],
                                            fontSize: 10,
                                            backgroundColor:'#ff9600',
                                            verticalAlign:'middle',
                                            borderRadius:[0,2,2,0]
                                        }
                                        
                                    }
                                
                            }
                        },
                        itemStyle: {
                            areaColor:'#eee', // 地图颜色
                            normal: {
                                label: {
                                    show: true
                                },
                                areaColor: { //地图显示渐变
                                    type: 'linear',
                                    x: 1,
                                    y: 1,
                                    x2: 0,
                                    y2: 0,
                                    colorStops: [
                                        { offset: 0, color: '#0c3a67' },
                                        { offset: 1, color: '#0c4179' }
                                    ],
                                    global: false // 缺省为 false
                                },
						        borderColor: '#53D9FF',
						        borderWidth: 1
                                
                            },
                            emphasis: { // 选中后颜色变化
                                label: {show: true},
                                areaColor: '#8dd7fc',
                                borderWidth: 1.6,
                                shadowBlur: 25,
                            }
                        },
                        data:dataList,
                        
                    }
                ]
            },true);
            //点击前解绑，防止点击事件触发多次
            myChart.off('click');
            myChart.on('click', echartsMapClick_lastMap);
                    
        })

}


function echartsMapClick_lastMap(params)
    {
		// 如果镇信息dataList没有定义过，params.data是undefined
		if(params.data)
		{
			alert(params.data.name+"---"+params.data.areaId);
		}

    }

function isShowLastMap(parentInfo)
{
	var hasLastMapProvince=[330000];
	var tag=false;
	parentInfo.forEach(function(item){
		if(hasLastMapProvince.includes(item.code))
		{
			tag=true;
		}
	})
	return tag;
}
</script>
</body>
</html>